function ProfileCtrl($scope, $http) {
	$scope.errorMessage = {};
	
	$scope.init = function() {
		$http.post('/user/currUser').success(function(response) {
			if (response.success) {
				$scope.user = response.success && response.data;
				$scope.user.password = '';
				$scope.email = $scope.user.email;
			} else {
				Message.error('错误', response.message || '操作失败');
			}
		});
	};
	
	$scope.save = function() {
		var user = {};
		
		if ($scope.mode == 'editEmail') {
			$scope.validateEmail();
			if($scope.vEmail) {
				return;
			}
			
			user = {
				username: $scope.user.username,
				email: $scope.email
			};
		} else if ($scope.mode == 'changePwd') {
			$scope.validatePassword();
			$scope.validateConfirmPwd();
			if($scope.vPassword || $scope.vConfirmPwd) {
				return;
			}
			
			user = {
				username: $scope.user.username,
				password: $scope.user.password
			};
		} else {
			return;
		}
		
		$http.post('/user/update', user).success(function(response) {
			if (response.success) {
				Message.info('提示', response.message || '操作成功', $scope.flushUser(user));
				$scope.mode = 'read';
			} else {
				Message.error('错误', response.message || '操作失败');
			}
		});
	};
	
	$scope.flushUser = function(user) {
		 $.extend($scope.user, user);
	};
	
	$scope.cancel = function() {
		$scope.mode = 'read';
		$scope.errorMessage = {};
		$scope.email = $scope.user.email;
		$scope.user.password = '';
		$scope.confirmPwd = '';
	};
	
	$scope.validatePassword = function() {
		if(!$scope.user.password) {
			$scope.confirmPwd = "";
			$scope.vPassword = true;
			$scope.errorMessage.password = "密码不能为空";
		} else if($scope.user.password.containsSpacialChar()) {
			$scope.errorMessage.password = "密码不能含有\" ' < > & ? # =特殊字符";
			$scope.vPassword = true;
		} else if($scope.user.password.length < 6 || $scope.user.password.length > 24) {
			$scope.errorMessage.password = "密码长度必须在6到24位之间";
			$scope.vPassword = true;
		} else {
			$scope.vPassword = false;
			$scope.errorMessage.password= '';
		};
	};
	
	$scope.validateConfirmPwd = function() {
		if(!$scope.confirmPwd) {
			$scope.vConfirmPwd = true;
			$scope.errorMessage.confirmPwd = "请输入确认密码";
		} else if($scope.confirmPwd != $scope.user.password) {
			$scope.vConfirmPwd = true;
			$scope.errorMessage.confirmPwd = "两次输入密码不一致";
		} else {
			$scope.vConfirmPwd = false;
			$scope.errorMessage.confirmPwd = '';
		}
	};
	
	$scope.validateEmail = function() {
		if(!$scope.email) {
			$scope.vEmail = true;
			$scope.errorMessage.email = "邮箱不能为空";
		} else if(!$scope.email.isValidEmail()) {
			$scope.vEmail = true;
			$scope.errorMessage.email = "邮箱格式有误";
		} else {
			$scope.vEmail = false;
			$scope.errorMessage.email = '';
		}
	};
	
	$scope.init();
};

app.controller('ProfileCtrl', ProfileCtrl);